<template>
    <view class="container" :class="tempType == 0 ? '' : 'p-b-120'">
        <search-bar :placeholderText="placeholderText" :scantions="scantions" :actions="actions" @searchFn="searchFn"
            @actionFn="actionFn">
        </search-bar>
        <tab-bar :tabs="tabs" @clickTab="clickTab" :tabIndex="tabIndex"></tab-bar>

        <view class="product-main">
            <scroll-view class="product-main-nav" scroll-y="true" :style="{ height: listHeight }">
                <nav-tree :tree-data="classifyList" :active-id="activeId" @treeClickEvent="treeClickEvent"></nav-tree>
            </scroll-view>
            <swiper class="swiper product-main-list" :class="tempType == 1 ? '' : 'p-b-120'"
                :style="{ height: listHeight }" :current="tabIndex" @change="swiperChange">
                <swiper-item v-if="loadOk" v-for="(swiperItem, swiperIndex) in tabs" :key="swiperIndex">
                    <product-list :ref="'productList_' + swiperIndex" :requestData="requestData" :height="listHeight"
                        :isHideProImg="isHideProImg" @sku="sku" :infoType="swiperIndex" :displayData="displayData"
                        :tempType="tempType" :valetUserId="valetUserId" :warehouseId="warehouseId" :isGift="isGift"
                        :isOnShow="isOnShow" @upFavorite="upFavorite" @isUpNum="isUpNum"
                        :getTempCartData="getTempCartData" :selectType="selectType" @loadNoMoreBack="loadNoMoreBack"
                        @inquire="inquire">
                    </product-list>
                </swiper-item>
            </swiper>
        </view>
        <uni-popup type="bottom" ref="popSku" @change="skuChange">
            <product-spec v-if="showPopSku" :data="optPopup.data" :tempType="tempType" :fresh="optPopup.change"
                :popup-type="optPopup.type" @closePopup="closePopup" @addCart="addCart" @addBatch="addBatch"
                @setCarListFunc="setCarListFunc" @inquire="inquire" :valetUserId="valetUserId" :isGift="isGift"
                :warehouseId="warehouseId" :selectType="selectType">
            </product-spec>
        </uni-popup>
        <uni-popup class="pop-check-cut" ref="inquirePop" type="center" :animation="false" :maskClick="false">
            <view class="pop-check-cut-box">
                <image src="@/static/img/close_one.png" class="closeimg" @click="closeInquire"></image>
                <view class="pop-tip" v-if="inquireList && inquireList[0]">
                    <image :src="easyGetImgUrl(inquireList[0].ProductImage)" mode="aspectFill"></image>
                    <view>{{ inquireList[0].ProductName }}</view>
                </view>
                <view class="pop-center">
                    <view>仓库</view>
                    <view>库存</view>
                </view>
                <scroll-view class="pop-bottom" v-if="inquireList && inquireList[0]" :scroll-y="true"
                    :show-scrollbar="false">
                    <view class="pop-bot-main" :class="{ activewarehouse: activeWarehouse == index }"
                        v-for="(item, index) in inquireList[0].Details" @click="selectWarehouse(item, index)">
                        <view>{{ item.WarehouseName }}</view>
                        <view>{{ item.Stock }}</view>
                    </view>
                </scroll-view>
                <view class="pop-bot-btn" @click="cutWarehouse">切换仓库</view>
            </view>
        </uni-popup>
        <uni-drawer :width="320" ref="showRight" mode="right" :mask-click="true">
            <view class="drawer-view">
                <scroll-view class="drawer-scroll" scroll-y="true">
                    <view class="filter-item tag-item">
                        <text class="label">排序</text>
                        <view class="tags">
                            <text class="tag-item" @click="selectSortFn(item, index)"
                                :class="{ selected: selectSort == index }" v-for="(item, index) in sortItems">{{
                                    item.name }}</text>
                        </view>
                    </view>
                    <view class="filter-item tag-item" v-if="false">
                        <text class="label">商品状态</text>
                        <view class="tags">
                            <text class="tag-item">已上架</text>
                            <text class="tag-item">已下架</text>
                        </view>
                    </view>
                    <view class="filter-item tag-item">
                        <text class="label">商品品牌</text>
                        <view class="tags" v-if="brandList.length > 0">
                            <text class="tag-item" v-for="(item, index) in brandList"
                                :class="{ selected: item.checked }" @click="changeBrand(index)">{{ item.Name }}</text>
                        </view>
                        <view v-else class="color3">该分类没有对应品牌</view>
                    </view>
                    <view class="filter-item tag-item">
                        <text class="label">商品标签</text>
                        <view class="tags" v-if="tagList.length > 0">
                            <text class="tag-item" v-for="(item, index) in tagList" :class="{ selected: item.checked }"
                                @click="changeTag(index)">{{ item.TagName }}</text>
                        </view>
                        <view v-else class="color3">暂无对应商品标签</view>
                    </view>
                    <view class="filter-item tag-item">
                        <text class="label">促销状态</text>
                        <view class="tags">
                            <!-- <text class="tag-item" >正常</text> -->
                            <text class="tag-item" :class="{ selected: isPromotion }"
                                @click="isPromotion = !isPromotion">促销</text>
                        </view>
                    </view>
                    <view class="filter-item tag-item" v-if="false">
                        <text class="label">商品价格</text>
                        <view class="tags">
                            <text class="tag-item">按高到低</text>
                            <text class="tag-item">按低到高</text>
                        </view>
                    </view>
                </scroll-view>
                <view class="drawer-bottom-bar">
                    <button class="btn btn-reset" @click="resetFn">
                        <text>重置</text>
                    </button>
                    <button class="btn btn-set" @click="setFn">
                        <text>确定</text>
                    </button>
                </view>
            </view>
        </uni-drawer>
    </view>
</template>

<script>
import { mapGetters } from "vuex"
import searchBar from "@/components/common/search-bar.vue"
import tabBar from "@/components/common/tab-bar.vue"
import productListFilter from "@/components/product/product-list-filter.vue"
import productList from "@/components/product/product-list.vue"
import navTree from "@/components/product/nav-tree.vue"
import productSpec from "@/components/product/product-spec.vue"
import { getElementHeight } from "@/uni-sub-base/utils/elementUtil.js"
import { getProductDisplay } from "@/utils/appInit.js"
import { GetProductWarehouseStockList } from "@/service/api/warehouse.js"
import { getProductTypeTree, productBrandList, getTagList } from "@/service/api/product.js"

export default {
    components: {
        searchBar,
        productListFilter,
        productList,
        tabBar,
        navTree,
        productSpec,
    },
    props: {
        //列表位置 0商品 1无单退货 2代客下单
        tempType: {
            type: Number,
            default: 0,
        },
        valetUserInfo: {
            type: String,
            default: () => { },
        },
        valetUserId: {
            type: Number,
            default: 0,
        },
        warehouseId: {
            type: Number,
            default: 0,
        },
        isGift: {
            type: String,
            default: "",
        },
        isOnShow: {
            type: Boolean,
            default: true,
        },
        getTempCartData: {
            type: Array,
            default: () => [],
        },
        selectType: {
            type: [Number, String],
            default: 0,
        },
    },
    computed: {
        ...mapGetters(["userInfo", "isLogin", "isManager"]),
    },
    methods: {
        // 切换商品分类
        changeClassify(id) {
        }
    },
    watch: {
        isOnShow(e) { },
    },
    data() {
        return {
            initClassify: false,
            activeId: -1,
            classifyList: [],
            skuModel: false,
            isHideProImg: false,
            actions: [
                {
                    type: "icon-shaixuan",
                    id: 2,
                },
            ],
            scantions: [
                // {
                // 	type: "icon-saoyisao",
                // 	id: 1
                // }
            ],
            placeholderText: "请输入商品名称",
            searchValue: "",
            tabIndex: 0,
            tabs: [
                {
                    title: "全部商品",
                },
                // {
                //     title: "常购清单",
                // },
            ],
            navHeight: 0, //nav所需高度
            listHeight: 0, //list所需高度
            productDatas: [],
            navItems: [],
            currentNav: 0,
            isloadding: false,
            loadOk: false,
            // sku 商品规格弹窗
            optPopup: {
                data: {},
                type: "",
                change: false,
                show: true,
            },
            isClosePop: false,
            treeOk: false,
            tags: [],
            brands: [],
            // 请求参数
            requestData: {
                ProductType: 1,
                OrderBy: "display_sequence",
                Sort: "desc",
                SecondaryOrderBy: "product_code",
                SecondarySort: "asc",
                infoType: 0,
            },
            displayData: {},
            showPopSku: true,
            timer: null,
            isUp: true,
            filterData: {
                warehouse: "",
            },
            brandList: [],
            tagList: [],
            isPromotion: false,
            inquireList: {},
            activeWarehouse: -1,
            sortItems: [
                // 排序方式列表
                {
                    name: "默认排序",
                    OrderBy: "display_sequence",
                    Sort: "desc",
                },
                {
                    name: "价格从低到高",
                    OrderBy: "grade_price",
                    Sort: "asc",
                },
                {
                    name: "价格从高到低",
                    OrderBy: "grade_price",
                    Sort: "desc",
                },
                {
                    name: "编码从低到高",
                    OrderBy: "product_code",
                    Sort: "asc",
                },
                {
                    name: "编码从高到低",
                    OrderBy: "product_code",
                    Sort: "desc",
                },
            ],
            selectSort: 0,
        }
    },
    watch: {},
    computed: {},
    onShow() {
        if (this.selectType != 4) {
            this.tabs.push({
                title: "常购清单",
            })
        }
    },
    mounted() {
        this.getListHeight()
        this.getProductTypeTree()

        this.GetProductDisplay()
    },
    methods: {
        selectWarehouse(item, index) {
            this.activeWarehouse = index
        },
        cutWarehouse() {
            if (this.activeWarehouse == -1) {
                this.easyToast("请先选择仓库")
                return
            }
            this.$emit("cutware", this.inquireList[0].Details[this.activeWarehouse].WarehouseId)
            this.closeInquire()
            this.$refs.popSku.close()
            setTimeout(() => {
                this.refresh()
            }, 300)
        },
        inquire(item) {
            let param = {}
            if (item.SkuId && item.ProductId) {
                param.productId = item.ProductId
                param.skuId = item.SkuId
            } else {
                param.productId = item.ID
                param.skuId = 0
            }
            GetProductWarehouseStockList(param).then((res) => {
                if (res.State == 1) {
                    this.inquireList = res.Data
                    this.activeWarehouse = -1
                    this.$refs.inquirePop.open()
                }
            })
        },
        closeInquire() {
            this.$refs.inquirePop.close()
        },
        // 获取整体显示设置
        GetProductDisplay() {
            getProductDisplay().then((res) => {
                if (res.State == 1) {
                    this.displayData = res.Data
                }
            })
        },
        //标签
        getTagList(categoryId, brandId) {
            let path = "?categoryId=0&brandIds=0"
            if (categoryId) {
                path = "?categoryId=" + categoryId + "&brandIds=0"
            }
            if (brandId) {
                path = "?categoryId=" + categoryId + "&brandIds=" + brandId
            }
            getTagList(path).then((res) => {
                this.tagList = res.Data
                this.$forceUpdate()
            })
        },
        //品牌
        productBrandList(id) {
            let path = "?categoryId=0"
            if (id) {
                path = "?categoryId=" + id
            }
            productBrandList(path).then((res) => {
                this.brandList = res.Data
                this.$forceUpdate()
            })
        },
        //商品分类树列表
        getProductTypeTree() {
            let param = {
                InfoType: 1,
                parent_path: "_0_2_",
            }
            getProductTypeTree(param).then((res) => {
                this.getNavData(res)
            })
        },
        getNavData(res) {
            if (res) {
                this.initClassify = false
                this.classifyList = []
                const totalClassify = {
                    OrderBy: res.Data.OrderBy,
                    id: res.Data.id,
                    name: res.Data.name,
                    parent_id: res.Data.parent_id,
                    parent_path: res.Data.parent_path,
                    type_id: res.Data.type_id,
                }
                this.classifyList.push(totalClassify)
                if (res.Data.children && res.Data.children.length > 0) {
                    // let arr = res.Data.children.slice(0, 10)
                    let arr = res.Data.children
                    arr.forEach((item) => {
                        this.classifyList.push(item)
                    })
                }
                this.activeId = res.Data.id
                this.productBrandList(this.activeId)
                this.getTagList(this.activeId, false)
                this.requestData.typePath = res.Data.parent_path
                setTimeout(() => {
                    this.refresh()
                }, 300)
            }
        },
        //刷新列表
        refresh() {
            if (this.$refs.productList_0 && this.$refs.productList_0[0]) {
                this.$refs.productList_0[0].refresh(this.requestData)
            }
            if (this.$refs.productList_1 && this.$refs.productList_1[0]) {
                this.$refs.productList_1[0].refresh(this.requestData)
            }
            // if (this.$refs.productList_2 && this.$refs.productList_2[0]) {
            // 	this.$refs.productList_2[0].refresh(this.requestData)
            // }
            // if (this.$refs.productList_3 && this.$refs.productList_3[0]) {
            // 	this.$refs.productList_3[0].refresh(this.requestData)
            // }
        },
        //收藏触发更新
        upFavorite(infoType) {
            console.log(infoType)
            if (infoType == 2) {
                if (this.$refs.productList_0 && this.$refs.productList_0[0]) {
                    this.$refs.productList_0[0].refresh(this.requestData)
                }
            } else if (infoType == 0) {
                if (this.$refs.productList_2 && this.$refs.productList_2[0]) {
                    this.$refs.productList_2[0].refresh(this.requestData)
                }
            }
        },
        getListHeight(element) {
            //获取商品高度
            getElementHeight(this, ".product-main", (e) => {
                this.listHeight = e - uni.upx2px(120) + "px"
                this.loadOk = true
                setTimeout(() => {
                    this.refresh()
                }, 300)
            })
        },
        searchFn(searchText) {
            //搜索
            this.requestData.search = searchText

            this.resetClass(this.classifyList[0])
        },
        resetClass(item) {
            this.activeId = item.id
            this.typePath = item.parent_path
            this.requestData.typePath = item.parent_path
            console.log(this.requestData)
            if (!this.isUp) {
                this.$emit("upCart", true)
                this.isUp = true
            }
            this.refresh()
        },
        actionFn(actionItem) {
            //功能点击
            if (actionItem.id == 1) {
                // this.scan()
                this.easyGoTo(
                    "/pages/product/scanCodes?valetUserId=" +
                    this.valetUserId +
                    "&valetUserInfo=" +
                    this.valetUserInfo +
                    "&warehouseId=" +
                    this.warehouseId,
                )
            } else if (actionItem.id == 2) {
                console.log("筛选")
                this.filterOpen()
            }
        },
        scan() {
            //扫一扫
            //#ifdef MP||APP-PLUS
            // 允许从相机和相册扫码
            uni.scanCode({
                success: function (res) {
                    uni.showToast({
                        title: "扫码结果:" + res.result,
                        icon: "none",
                        duration: 2000,
                    })
                },
            })
            //#endif
        },
        changeListTheme(isShow) {
            //切换商品列表无图显示
            this.displayData.IsShowImg = isShow
            this.$forceUpdate()
        },
        sku(item) {
            this.showPopSku = true
            this.optPopup.type = "attr"
            this.optPopup.data = item
            this.$refs.popSku.open()
        },
        addCart(e) {
            this.$refs.popSku.close()
        },
        addCartBatch(e) {
            console.log(e)
        },
        addBatch(e) {
            this.$refs.popSku.close()
            this.$refs.popBatch.open()
        },
        buyNow() { },
        swiperChange(e) {
            let tabIndex = e.detail.current
            this.clickTab(tabIndex)
        },
        //tab切换
        clickTab(index) {
            if (this.tabIndex != index) {
                clearTimeout(this.timer)
                this.timer = setTimeout((time) => {
                    this.tabIndex = index
                    this.requestData.infoType = index
                }, 20)
                if (!this.isUp) {
                    this.$emit("upCart", true)
                    this.isUp = true
                }
            }
        },
        // 点击分类事件
        treeClickEvent(item) {
            if (this.activeId !== item.id) {
                this.activeId = item.id
                this.typePath = item.parent_path
                this.requestData.typePath = item.parent_path
                console.log(this.requestData)
                if (!this.isUp) {
                    this.$emit("upCart", true)
                    this.isUp = true
                }
                this.requestData.BrandIds = ""
                this.requestData.TagIds = ""
                this.cancelFilterBrands()
                this.cancelFilterTags()
                this.productBrandList(item.id)
                this.getTagList(item.id, false)
                this.refresh()
            }
        },
        closePopup() {
            this.$refs.popSku.close()
        },
        setCarListFunc() {
            this.$forceUpdate()
        },
        closePopupBatch() {
            this.$refs.popBatch.close()
        },
        setCarListFuncBatch() {
            this.$forceUpdate()
        },
        filterBrandFn(data) {
            let ids = []
            data.forEach((e) => {
                if (e.checked) {
                    ids.push(e.Id)
                }
            })
            this.requestData.BrandIds = ids.join(",")
            this.refresh()
        },
        filterTagFn(data) {
            let ids = []
            data.forEach((e) => {
                if (e.checked) {
                    ids.push(e.Id)
                }
            })
            this.requestData.TagIds = ids.join(",")
            this.refresh()
        },
        skuChange(e) {
            if (!e.show) {
                this.showPopSku = false
                // this.$nextTick(e=>{
                // 	this.showPopSku = true
                // })
            }
        },
        isUpNum(e) {
            this.isUp = e
        },
        filterOpen() {
            this.$refs.showRight.open()
        },
        filterClose() {
            this.$refs.showRight.close()
        },
        checkUseBarnd() {
            return this.brandList.find((item) => {
                return item.checked
            })
        },
        checkUseTag() {
            return this.tagList.find((item) => {
                return item.checked
            })
        },
        // 修改品牌筛选
        changeBrand(index) {
            console.log(index)
            this.brandList[index].checked = !this.brandList[index].checked
            let ids = []
            this.brandList.forEach((e) => {
                if (e.checked) {
                    ids.push(e.ID)
                }
            })
            this.getTagList(this.activeId, ids.join(","))
            this.$forceUpdate()
        },
        // 修改标签筛选
        changeTag(index) {
            this.tagList[index].checked = !this.tagList[index].checked
            this.$forceUpdate()
        },
        //重置品牌
        cancelFilterBrands() {
            this.brandList.forEach((e) => {
                e.checked = false
            })
            this.$forceUpdate()
        },
        //重置标签
        cancelFilterTags() {
            this.tagList.forEach((e) => {
                e.checked = false
            })
            this.$forceUpdate()
        },
        setFn() {
            if (this.isPromotion) {
                this.requestData.isPromotion = this.isPromotion
            } else {
                this.requestData.isPromotion = false
            }
            this.filterBrandFn()
            this.filterTagFn()
            this.refresh()
            this.filterClose()
        },
        resetFn() {
            this.isPromotion = false
            this.cancelFilterBrands()
            this.cancelFilterTags()
            this.getTagList(this.activeId, false)
            this.setFn()
            this.selectSort = 0
            this.requestData.OrderBy = "display_sequence"
            this.requestData.Sort = "desc"
        },
        filterBrandFn() {
            let ids = []
            this.brandList.forEach((e) => {
                if (e.checked) {
                    ids.push(e.ID)
                }
            })
            this.requestData.BrandIds = ids.join(",")
        },
        filterTagFn() {
            let ids = []
            this.tagList.forEach((e) => {
                if (e.checked) {
                    ids.push(e.ID)
                }
            })
            this.requestData.TagIds = ids.join(",")
        },
        selectSortFn(item, index) {
            this.selectSort = index
            this.requestData.OrderBy = item.OrderBy
            this.requestData.Sort = item.Sort
        },
        loadNoMoreBack(e) {
            if (e) {
                let objItem = {}
                let hasIn = false
                if (this.activeId == this.classifyList[0].id) {
                    //当前是全部分类
                    this.treeClickEvent(this.classifyList[1])
                } else {
                    for (var i = 0; i < this.classifyList.length; i++) {
                        let item = this.classifyList[i]
                        if (item.id == this.activeId) {
                            //判断当前是否是大类
                            this.hasIn = true
                            if (i != this.classifyList.length - 1) {
                                objItem = this.classifyList[i + 1]
                            } else {
                                objItem = this.classifyList[0]
                            }
                            this.treeClickEvent(objItem)
                            return
                        }
                    }
                    if (!hasIn) {
                        for (var i = 1; i < this.classifyList.length; i++) {
                            let item = this.classifyList[i]
                            let path = item.parent_path
                            if (this.typePath.includes(path)) {
                                let item = this.classifyList[i]
                                if (i != this.classifyList.length - 1) {
                                    objItem = this.classifyList[i + 1]
                                } else {
                                    objItem = this.classifyList[0]
                                }
                                this.treeClickEvent(objItem)
                                return
                            }
                        }
                    }
                }
            }
        },
    },
}
</script>

<style lang="scss">
.product-main {
    display: flex;
    flex-direction: row;

    .product-main-nav {
        display: flex;
        flex: 1;
        flex-direction: column;
        background: $uni-bg-color-grey;
    }

    .product-main-list {
        display: flex;
        flex: 3;
        justify-content: center;
        background: $uni-bg-color-grey;
    }

    .p-b-120 {
        padding-bottom: 120rpx;
    }
}

.swiper {
    background: $color-white;
}

.pop-check-cut-box {
    position: relative;
    width: 640rpx;
    background: #ffffff;
    border-radius: 24rpx;
    padding-bottom: 24rpx;

    .closeimg {
        width: 64rpx;
        height: 64rpx;
        position: absolute;
        right: -32rpx;
        top: -32rpx;
    }

    .pop-tip {
        padding: 24rpx;
        display: flex;
        align-items: center;
        font-size: 32rpx;
        color: #333;
        background: #f4f5f6;
        border-radius: 24rpx 24rpx 0 0;

        image {
            width: 128rpx;
            height: 128rpx;
            border-radius: 8rpx;
            margin-right: 24rpx;
        }
    }

    .pop-center {
        display: flex;
        justify-content: space-between;
        padding: 12rpx 80rpx 12rpx 100rpx;
        background: #f4f5f6;
        font-size: 26rpx;
        color: #666666;
    }

    .pop-bottom {
        margin-bottom: 24rpx;
        max-height: 500rpx;

        .pop-bot-main {
            padding: 0 70rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 32rpx;
            color: #333;
            height: 100rpx;
            background: #ffffff;
        }

        .activewarehouse {
            font-weight: bold;
            color: $app-color-main;
        }
    }

    .pop-bot-btn {
        width: 220rpx;
        height: 80rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: $app-color-main;
        border-radius: 45px;
        font-size: 32rpx;
        color: #ffffff;
        margin: 0 auto;
    }
}

.color3 {
    color: $color-gray-3;
    font-size: 24rpx;
}
</style>
